/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.common.dao.openjpa;

import org.apache.openjpa.jdbc.identifier.DBIdentifier;
import org.apache.openjpa.jdbc.schema.Column;
import org.apache.openjpa.jdbc.schema.Table;
import org.apache.openjpa.persistence.jdbc.PersistenceMappingDefaults;

import com.ibm.iisp.common.util.StringUtilsExt;

/**
 * 类作用：改善数据库字段命名规则，变成"_"分隔，如user_name
 *
 * @author Johnny@cn.ibm.com
 *
 *         使用说明：
 *
 *         &lt;prop
 *         key="openjpa.jdbc.MappingDefaults"&gt;com.ibm.iisp.common.dao.openjpa
 *         .ImprovedMappingStrategy&lt;/prop&gt;
 */
public class ImprovedMappingStrategy extends PersistenceMappingDefaults {

	@Override
	protected void correctName(Table table, Column col) {
		DBIdentifier name = col.getIdentifier();
		String _name = addUnderscores(name.getName());
		name.setName(_name);
	}

	// taken from Hibernate's ImprovedNamingStrategy
	private static String addUnderscores(String name) {
		return StringUtilsExt.toUnderscopeSeperated(name);
//		StringBuilder buf = new StringBuilder(name.replace('.', '_'));
//		for (int i = 1; i < buf.length() - 1; i++) {
//			if (Character.isLowerCase(buf.charAt(i - 1)) && Character.isUpperCase(buf.charAt(i))
//			        && Character.isLowerCase(buf.charAt(i + 1))) {
//				buf.insert(i++, '_');
//			}
//		}
//		return buf.toString().toLowerCase();
	}
}